﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Vit.Common;
using Vit.Common.Providers;
using Vit.Web.Models;

namespace Vit.Web.SqlProviders
{
    public class SqlLogProvider : Vit.Common.Providers.Logging.WebLogProviderBase
    {
        private WebProvidersDb db = new WebProvidersDb();

        public override void Log(LogInfo logInfo)
        {
            Models.Log log = new Log()
            {
                ID = Guid.NewGuid().ToString(),
                RequestUrl = logInfo.RequestUrl,
                Source = logInfo.Source,
                Message = logInfo.Message,
                Details = logInfo.Details,
                ContextInfo = CreateContextInfo(),
                LogLevel = logInfo.LogLevel,
                Level = (int)logInfo.LogLevel,
                LogTime = DateTime.Now
            };

            db.Logs.Add(log);
            db.SaveChanges();
        }

        public override void Log(Exception exception)
        {
            Log(exception, LogLevel.Error);
        }

        public override void Log(string source, string message)
        {
            Log(source, message, LogLevel.Info);
        }

        public override void Log(Exception exception, LogLevel logLevel)
        {
            exception = exception.GetBaseException();
            LogInfo info = new LogInfo()
            {
                Source = exception.Source,
                Message = exception.Message,
                Details = exception.StackTrace,
                LogLevel = logLevel
            };
            Log(info);
        }

        public override void Log(string source, string message, LogLevel logLevel)
        {
            LogInfo info = new LogInfo()
            {
                Source = source,
                Message = message,
                LogLevel = logLevel
            };
            Log(info);
        }

        public override void RemoveAll(DateTime beforeDate)
        {
            string sql = "DELETE dbo.Logs WHERE LogTime<=@0";
            db.Database.ExecuteSqlCommand(sql, beforeDate);
        }

        public override void Clear()
        {
            string sql = "DELETE dbo.Logs";
            db.Database.ExecuteSqlCommand(sql);
        }
    }
}
